package com.llkj.qingnianguoxue.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import com.baidu.platform.comapi.map.F;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import static com.llkj.qingnianguoxue.util.Utils.IMAGE_UNSPECIFIED;

/**
 * Created by dyz on 2019/2/27.
 */

public class SelectPictureUtil {
    public static final int INTENT_REQUEST_CODE_PICK = 0; // 相册选择标记
    public static final int INTENT_REQUEST_CODE_TAKE = 1; // 相机拍照标记
    public static final int INTENT_REQUEST_CODE_CUTTING = 2; // 图片裁切标记
    public static final String IMAGE_FILE_NAME = "take_photo.jpg";// 头像文件名称
    private Activity mContext;
//    private Uri mCropFileUri;//裁剪图片输出Uri
    private File mCropFile;//裁剪输出图片
    private File mCameraFile;//拍照输出文件
    private int mCropOutputWidth = 300,mCropOutputHeight = 300;//裁剪输出宽高，默认300px
    private SelectPictureResultCallback mResultCallback;//裁剪成功回调

    /**
     *
     * @param mContext
     */
    public SelectPictureUtil(Activity mContext,SelectPictureResultCallback listener) {
        this.mContext = mContext;
        this.mResultCallback = listener;
    }

    /**
     * 设置裁剪输出图片宽高，返回裁剪结果回调
     * @param mCropOutputWidth
     *  裁剪输出宽高
     * @param mCropOutputHeight
     */
    public void setCropWidthHeight(int mCropOutputWidth, int mCropOutputHeight) {
        this.mContext = mContext;
        this.mCropOutputWidth = mCropOutputWidth;
        this.mCropOutputHeight = mCropOutputHeight;
    }

    /**
     * 拍照
     * @return
     */
    public File takePhoto() {
        mCameraFile = new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(mContext.getPackageManager()) != null) {
            Uri uri = FileProvider7.getUriForFile(mContext, mCameraFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            mContext.startActivityForResult(intent, INTENT_REQUEST_CODE_TAKE);
        }
        return mCameraFile;
    }

    /**
     * 相册
     */
    public void album() {
        Intent pickIntent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        mContext.startActivityForResult(pickIntent, INTENT_REQUEST_CODE_PICK);
    }

    /**
     * 拍照/相册/裁剪回调,在Activity onActivityResult中调用
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == INTENT_REQUEST_CODE_PICK && data != null) {// 直接从相册获取
            startPhotoZoom(data.getData());
        } else if (requestCode == INTENT_REQUEST_CODE_TAKE && mCameraFile != null) {// 调用相机拍照
            startPhotoZoom(FileProvider7.getUriForFile(mContext, mCameraFile));
        } else if (requestCode == INTENT_REQUEST_CODE_CUTTING && data != null) {// 取得裁剪后的图片
            try {
//                Bitmap bitmap = BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(mCropFileUri));
                File file = mCropFile;
                if(mResultCallback!=null && file!=null && file.exists()){
                    mResultCallback.onCropResult(file);
                }
//                mCropFileUri = null;
//                bitmap.recycle();
//                bitmap = null;
            } catch (Exception e) {}
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        createFile();
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        FileProvider7.grantPermissions(mContext, intent, uri, true);
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("scale", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", mCropOutputWidth);
        intent.putExtra("aspectY", mCropOutputHeight);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", mCropOutputWidth);
        intent.putExtra("outputY", mCropOutputHeight);

        intent.putExtra("return-data", false);
//        String path = getAppDir(mContext)+"/crop_image"+"/crop_" + System.currentTimeMillis()+".jpg";
//        mCropFileUri = Uri.parse("file://" + "/" + path);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCropFile));
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        mContext.startActivityForResult(intent, INTENT_REQUEST_CODE_CUTTING);
    }

    private void createFile(){
        try {
            File dir = new File(getAppDir(mContext), "crop_image");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String fileName = "crop_" + System.currentTimeMillis()+".jpg";
            mCropFile = new File(dir, fileName);
            if (mCropFile.exists()) {
                mCropFile.delete();
            }
            mCropFile.createNewFile();
        }catch (Exception e){}
    }

    /**
     * 保存图片到指定目录
     *
     * @param
     */
    private File saveBitmap(Context context, Bitmap mBitmap, String fileName) throws IOException {
        // 首先保存图片
        File dir = new File(getAppDir(context), "crop_image");
        if (dir == null) {
            Log.e("", "未找到存储位置");
            return null;
        }
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, fileName);
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
        return file;
    }

    public static String getAppDir(Context context) {
        return (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState()) ? (Environment
                .getExternalStorageDirectory().getPath() + "/Android/data/")
                : (context.getCacheDir().getPath()))
                + context.getPackageName();
    }

    public interface SelectPictureResultCallback{
        void onCropResult(File file);
    }
}
